import { apiClient } from './api'
import { authState } from './auth'
import { showError, showSuccess } from './notification'
import type { Folder, Note, SyncResult, SyncStatusInfo } from '../types'

/**
 * CRUD API服务
 * 直接对接后端的增删改查接口
 */

// 重新导出类型以保持向后兼容
export type { Folder, Note }

/**
 * 文件夹CRUD操作
 */
export class FolderAPI {
  /**
   * 获取所有文件夹
   */
  static async getAll(): Promise<Folder[]> {
    try {
      const response = await apiClient.get('/folders/')
      if (response.success && response.data) {
        // DRF可能返回分页格式或直接数组
        const folders = Array.isArray(response.data) ? response.data : response.data.results || []
        return folders.map((folder: any) => ({
          ...folder,
          syncStatus: 'synced'
        }))
      }
      throw new Error(response.error || '获取文件夹失败')
    } catch (error) {
      console.error('获取文件夹失败:', error)
      showError('获取文件夹失败')
      return []
    }
  }

  /**
   * 创建文件夹
   */
  static async create(folderData: Omit<Folder, 'id' | 'syncStatus'>): Promise<Folder | null> {
    try {
      const response = await apiClient.post('/folders/', folderData)
      if (response.success && response.data) {
        return {
          ...response.data,
          syncStatus: 'synced'
        }
      }
      throw new Error(response.error || '创建文件夹失败')
    } catch (error) {
      console.error('创建文件夹失败:', error)
      showError('创建文件夹失败')
      return null
    }
  }

  /**
   * 更新文件夹（部分更新）
   */
  static async update(id: number, folderData: Partial<Folder>): Promise<Folder | null> {
    try {
      const response = await apiClient.patch(`/folders/${id}/`, folderData)
      if (response.success && response.data) {
        return {
          ...response.data,
          syncStatus: 'synced'
        }
      }
      throw new Error(response.error || '更新文件夹失败')
    } catch (error) {
      console.error('更新文件夹失败:', error)
      showError('更新文件夹失败')
      return null
    }
  }

  /**
   * 删除文件夹
   */
  static async delete(id: number): Promise<boolean> {
    try {
      const response = await apiClient.delete(`/folders/${id}/`)
      if (response.success) {
        return true
      }
      throw new Error(response.error || '删除文件夹失败')
    } catch (error) {
      console.error('删除文件夹失败:', error)
      showError('删除文件夹失败')
      return false
    }
  }

  /**
   * 批量更新文件夹排序
   */
  static async batchUpdateOrder(folders: Array<{id: number, sortOrder: number}>): Promise<boolean> {
    try {
      const response = await apiClient.post('/folders/batch_update_order/', {
        folders: folders
      })
      if (response.success) {
        console.log('批量更新文件夹排序成功:', response.data?.message)
        return true
      }
      throw new Error(response.error || '批量更新排序失败')
    } catch (error) {
      console.error('批量更新文件夹排序失败:', error)
      showError('批量更新排序失败')
      return false
    }
  }
}

/**
 * 笔记CRUD操作
 */
export class NoteAPI {
  /**
   * 获取所有笔记
   */
  static async getAll(): Promise<Note[]> {
    try {
      const response = await apiClient.get('/notes/')
      if (response.success && response.data) {
        // DRF可能返回分页格式或直接数组
        const notes = Array.isArray(response.data) ? response.data : response.data.results || []
        return notes.map((note: any) => ({
          ...note,
          syncStatus: 'synced'
        }))
      }
      throw new Error(response.error || '获取笔记失败')
    } catch (error) {
      console.error('获取笔记失败:', error)
      showError('获取笔记失败')
      return []
    }
  }

  /**
   * 创建笔记
   */
  static async create(noteData: Omit<Note, 'id' | 'syncStatus'>): Promise<Note | null> {
    try {
      const response = await apiClient.post('/notes/', noteData)
      if (response.success && response.data) {
        return {
          ...response.data,
          syncStatus: 'synced'
        }
      }
      throw new Error(response.error || '创建笔记失败')
    } catch (error) {
      console.error('创建笔记失败:', error)
      showError('创建笔记失败')
      return null
    }
  }

  /**
   * 更新笔记（部分更新）
   */
  static async update(id: number, noteData: Partial<Note>): Promise<Note | null> {
    try {
      const response = await apiClient.patch(`/notes/${id}/`, noteData)
      if (response.success && response.data) {
        return {
          ...response.data,
          syncStatus: 'synced'
        }
      }
      throw new Error(response.error || '更新笔记失败')
    } catch (error) {
      console.error('更新笔记失败:', error)
      showError('更新笔记失败')
      return null
    }
  }

  /**
   * 删除笔记
   */
  static async delete(id: number): Promise<boolean> {
    try {
      const response = await apiClient.delete(`/notes/${id}/`)
      if (response.success) {
        return true
      }
      throw new Error(response.error || '删除笔记失败')
    } catch (error) {
      console.error('删除笔记失败:', error)
      showError('删除笔记失败')
      return false
    }
  }
}

/**
 * 离线状态管理
 * 未登录时保存本地并标记为未同步
 */
export class OfflineManager {
  private static readonly PENDING_FOLDERS_KEY = 'linkbook-pending-folders'
  private static readonly PENDING_NOTES_KEY = 'linkbook-pending-notes'

  /**
   * 添加待同步的文件夹
   */
  static addPendingFolder(folder: Folder): void {
    const pending = this.getPendingFolders()
    pending.push({ ...folder, syncStatus: 'pending' })
    localStorage.setItem(this.PENDING_FOLDERS_KEY, JSON.stringify(pending))
  }

  /**
   * 添加待同步的笔记
   */
  static addPendingNote(note: Note): void {
    const pending = this.getPendingNotes()
    pending.push({ ...note, syncStatus: 'pending' })
    localStorage.setItem(this.PENDING_NOTES_KEY, JSON.stringify(pending))
  }

  /**
   * 获取待同步的文件夹
   */
  static getPendingFolders(): Folder[] {
    try {
      const stored = localStorage.getItem(this.PENDING_FOLDERS_KEY)
      return stored ? JSON.parse(stored) : []
    } catch (error) {
      console.error('获取待同步文件夹失败:', error)
      return []
    }
  }

  /**
   * 获取待同步的笔记
   */
  static getPendingNotes(): Note[] {
    try {
      const stored = localStorage.getItem(this.PENDING_NOTES_KEY)
      return stored ? JSON.parse(stored) : []
    } catch (error) {
      console.error('获取待同步笔记失败:', error)
      return []
    }
  }

  /**
   * 同步所有待同步数据
   */
  static async syncPendingData(): Promise<SyncResult> {
    if (!authState.isLoggedIn) {
      console.log('用户未登录，跳过同步')
      return { success: true, failedCount: 0, totalCount: 0 }
    }

    console.log('开始同步待同步数据...')
    
    const pendingFolders = this.getPendingFolders()
    const pendingNotes = this.getPendingNotes()
    const totalCount = pendingFolders.length + pendingNotes.length
    
    if (totalCount === 0) {
      console.log('没有待同步的数据')
      return { success: true, failedCount: 0, totalCount: 0 }
    }

    let failedFolders: Folder[] = []
    let failedNotes: Note[] = []
    let successCount = 0

    // 同步文件夹
    for (const folder of pendingFolders) {
      try {
        const createdFolder = await FolderAPI.create(folder)
        if (createdFolder) {
          console.log(`文件夹同步成功: ${folder.name}`)
          successCount++
        } else {
          throw new Error('创建失败')
        }
      } catch (error) {
        console.error(`文件夹同步失败: ${folder.name}`, error)
        failedFolders.push(folder)
      }
    }

    // 同步笔记
    for (const note of pendingNotes) {
      try {
        const createdNote = await NoteAPI.create(note)
        if (createdNote) {
          console.log(`笔记同步成功: ${note.title}`)
          successCount++
        } else {
          throw new Error('创建失败')
        }
      } catch (error) {
        console.error(`笔记同步失败: ${note.title}`, error)
        failedNotes.push(note)
      }
    }

    const failedCount = failedFolders.length + failedNotes.length
    
    // 只清除成功同步的数据，保留失败的数据
    if (successCount > 0) {
      // 更新待同步列表，只保留失败的项目
      localStorage.setItem(this.PENDING_FOLDERS_KEY, JSON.stringify(failedFolders))
      localStorage.setItem(this.PENDING_NOTES_KEY, JSON.stringify(failedNotes))
    }
    
    console.log(`同步完成: 成功 ${successCount}/${totalCount}, 失败 ${failedCount}`)
    
    return {
      success: failedCount === 0,
      failedCount,
      totalCount
    }
  }

  /**
   * 清除待同步数据
   */
  static clearPendingData(): void {
    localStorage.removeItem(this.PENDING_FOLDERS_KEY)
    localStorage.removeItem(this.PENDING_NOTES_KEY)
  }

  /**
   * 获取待同步数据数量
   */
  static getPendingCount(): number {
    return this.getPendingFolders().length + this.getPendingNotes().length
  }
  
  /**
   * 重试同步失败的数据
   */
  static async retrySyncPendingData(): Promise<SyncResult> {
    console.log('重试同步待同步数据...')
    return await this.syncPendingData()
  }
  
  /**
   * 获取同步状态信息
   */
  static getSyncStatus(): SyncStatusInfo {
    const pendingFolders = this.getPendingFolders()
    const pendingNotes = this.getPendingNotes()
    const totalCount = pendingFolders.length + pendingNotes.length
    
    return {
      hasPendingData: totalCount > 0,
      pendingCount: totalCount,
      folders: pendingFolders.length,
      notes: pendingNotes.length
    }
  }
}